$.fn.grid = function(options) {
	//默认属性
	var defaultopts = {
		bgcolor: "#87CEFA"
	};
	$.extend(options, defaultopts);
	var $tbody = $(this).find("tbody");
	var colums = options.colums;
	var url = options.url;
	var content = [];
	$.ajax({
		type: "get",
		url: url,
		dataType: "json",
		async: false,
		success: function(data) {
			content = data;
		}
	});
	//添加数据
	for(var c = 0; c < content.length; c++) {
		//遍历所有列
		var cols = [];
		var id;
		$.each(colums, function(key, value) {
			//遍历json数据
			$.each(content[c], function(key2, value2) {
				if(key2 == "id") id = value2;
				if(key2 == value.Index) {
					//特殊值替换
					if(value.formatter != null) {
						$.each(value.formatter, function(k3, v3) {
							value2 = value2 == k3 ? v3 : value2;
						});
					}
					cols.push(value2);
					//delete content[c][key2];
				}
			});
		});
		var html;
		if(id != null) {
			html = "<tr grid-id='" + id + "'>";
		} else {
			html = "<tr>";
		}
		$.each(cols, function(k, v) {
			html += "<td>" + v + "</td>"
		});
		html += "</tr>";
		$tbody.append(html)
	}

	var selected_tr = {
		now: null, //当前选中的tr
		last: null //上一个选中的tr
	};
	//给每一个tr添加点击事件
	if(typeof(options.rowclick) == "function") {
		$.each($tbody.find("tr"), function(k, v) {
			$(v).click(function() {
				options.rowclick($(v).attr("grid-id"));
				
				selected_tr.last = selected_tr.now;
				selected_tr.now = v;
				$(selected_tr.last).removeAttr("bgcolor");
				$(selected_tr.now).attr("bgcolor", "#87CEFA");
				
				//如果点击的是已近选中的项，那么取消选中。
				if(selected_tr.now == selected_tr.last && selected_tr.last != null){
					$(selected_tr.last).removeAttr("bgcolor");
					selected_tr.last = selected_tr.now;
					selected_tr.now = null;
				}
			});
		});
	}
}